<?php
namespace app\api\controller;
// namespace app\zw_admin\controller;
use \think\Controller;
use think\Db;
// use think\Controller;
use think\Session;
use think\Request;
use Endroid\QrCode\Tests;
use qrcode;
use alisms\SmsDemo;
use Payment\Common\PayException;
use Payment\Client\Charge;
use think\Cache;
class AlipayController extends Controller
{


    public function alipay()
    {
        // echo '111';
        include_once ROOT_PATH.'extend/alipay/AopSdk.php';
        // $number = input('param.');
        $merge_number = input('param.merge_number');
        $uid = input('param.uid');

        if (empty($merge_number)) {
            echo json_encode(array("status"=>3,'message'=>'没有可交易订单!',"data"=>[]));
            exit;
        }

        $merge_order_list = db('merge_order')->where(['merge_number'=>$merge_number])->find();
        if ($merge_order_list['ali_type'] == '1') {
            echo json_encode(array("status"=>3,'message'=>'请不要重复交易!',"data"=>[]));
            exit;
        }
        // dump($order)
        if (empty($merge_order_list)) {
            echo json_encode(array("status"=>3,'message'=>'没有可交易订单!',"data"=>[]));
            exit;
        }

        $number = $merge_number;
        $body = '莫愁商城';
        $subject = '莫愁商城';
        $expire = '700';
        // $callback = "http://www.mochoushop.com/api/alipay/alipay_black";
        $pre_price = $merge_order_list['money'];
        // $pre_price = '0.01';
        // echo $number.'-'.$body.'-'.$subject.'-'.$expire.$pre_price;
        // exit;
        // $pre_price = '0.01';
        try{
            $aop = new \AopClient();
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
            $aop->appId = "2018071360723002";
            $aop->rsaPrivateKey = "MIIEpAIBAAKCAQEAwK99IOj0b1d/XjJsDRQ4yWIjfXGOIhds1fXK6lrAzCxY5YUG7EWzA660taBS+xaGG7MozeZEIIhua+AFs+FJ6WfcQkmmXQlT3iZO2RMbikb7fMAvgUf916CnpcHcTaUo/G8sgI8zoM06zNbAMrqIAhwJEEm5oN6jBHT5v9elbtoLtPgIpUrq8pNhOWBus8JUN9PojcDcL95JfnvJVJt1gmAl9X5ai5xqqLtgY6f0TnFfOpPIA9NBH1c24Qy2JJ8RHb/NOZlun4grTMb/COhVlXo9L/90YV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LNcTxgZXDj7b35N06z2fTLQKBgQCnoUX2c/9qnsvyY9wBA7rbunUJZEbWZnZzIWg1dz1JefqiITCn8/+mRj1TUbh7wzqR2cygNxBg9JrkHhgZS3FG8nuUHkQViwtizj2STjsRpuGOh6H+NawaeV9uM9oq/225ub3869gsnmPlJnw1zqW3m+roCAxw707P1chVuEnB5Q==";
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtkUtWxCXkAvcJGPIRtKhJSFdzxWblawi91kASYkkWqgqgl80CJqxjtEaQnN8BAq9CKoHL3wwMuVeDh6WRTVN4P+/Ie1I4F509NRyUXXg9EykET7M8uuOQyO9tud8kyWcmBzIR3Ltp6j+MwMwkE9+3NxChABM1n+AnfDMEoDrWJWgTDb8X/AlidtZ/kmXDLYNM7HbRwZ/cLMmbRFh8p7E5wosuZDR7S4tgTZaxFwnycK/e9IWV+Zw2Fl6zWFaAaIBqPzo/K+0sc70gdHwaRQw+TGrg8gE62Uid0p2q5reJ5QMUzCrKpNuCndKCv0QANTR74el0aTYv0OrmUbGTTJpgQIDAQAB";
            //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
            $request = new \AlipayTradeAppPayRequest();

            //SDK已经封装掉了公共参数，这里只需要传入业务参数
            $bizcontent = "{\"body\":\"{$body}\","      //支付商品描述
                . "\"subject\":\"{$subject}\","        //支付商品的标题
                . "\"out_trade_no\":\"{$number}\","   //商户网站唯一订单号
                . "\"timeout_express\":\"{$expire}m\","       //该笔订单允许的最晚付款时间，逾期将关闭交易
                . "\"total_amount\":\"{$pre_price}\"," //订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";

            $request->setNotifyUrl("http://www.mochoushop.com/api/alipay/alipay_black");
            //      dump($order_list);
            // exit;
            $request->setBizContent($bizcontent);
            //这里和普通的接口调用不同，使用的是sdkExecute
            $response = $aop->sdkExecute($request);
            
            echo json_encode(array("status"=>1,'message'=>'请求成功!',"data"=>$response));
            exit;
            // echo $response;
            // exit;
            // //htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
            // return htmlspecialchars($response);//就是orderString 可以直接给客户端请求，无需再做处理。
        }catch (\Exception $e){
            return false;
        }

    }


    /**
     * 支付宝处理结果回调
     * @return [type] [description]
     */
    public function alipay_black()
    {
        $list = input('param.');
        $trade_status = input('param.trade_status');
        
        if ($trade_status == 'TRADE_SUCCESS') {//如果支付成功
        	// cache('out_trade_no', $list['out_trade_no'], 3600);
        	// cache('alilist', $list, 3600);
         //===============修改订单状态业务处理===========================//
            /**
             * 获取交易订单信息
             */
            $merge_order_list = db('merge_order')->where(['merge_number'=>$list['out_trade_no']])->find();
            /**
             * 根据交易订单  获取商品订单信息
             */
            $number_list = explode(",",$merge_order_list['number']);
            $number = null;
            foreach ($number_list as $key => $value) {
                 $number .= "`number`="."'".$value."'"." or ";
            }
            $number = rtrim($number,'or ');
            $order_list = db('goods_order')->where($number)->select();
            // dump($order_list);
            // exit;
            $goodsNumber = null;
            foreach ($order_list as $key => $value) {
                 $goodsNumber .= "`number`="."'".$value['number']."'"." or ";
            }
            $goodsNumber = rtrim($goodsNumber,'or ');
           
           	$goodsList = db('goods')->where($goodsNumber)->select();
           	foreach ($goodsList as $key => $value) {
           			$where = [
           				'out_request_no' => $list['trade_no'].$value['goods_id']
           			];
           			db('goods')->where(['goods_id'=>$value['goods_id']])->update($where);
           	}
           	// dump($goodsList);
           	// exit;
            /**
             * 获取用户信息
             */
            $account = db('account')->where(['uid'=>$merge_order_list['uid']])->find();
            /**
             * 累积合计金额
             * @var [type]
             */
            $count = null;
            foreach ($order_list as $key => $value) {
                // dump($value['total']);
                $count += $value['total'] + $value['freight'];
            }

            /**
             * 进行积分->余额减扣;
             * 
             */
            if($account['balance'] > $count){
                $account_list['balance'] = $account['balance'] - $count; //剩余余额
                $reduce_balance = $account['balance'] - $account_list['balance']; //扣除余额
                $end_total = '0';
            }else{
                $end_total = $count - $account['balance']; //支付金额
                $reduce_balance = $count - $end_total; //扣除余额
                $account_list['balance'] = '0'; //剩余余额
            }
            // echo $reduce_balance;
            // exit;
            /**
             * 将剩下的余额存入数据库
             */
            db('account')->where(['uid'=>$merge_order_list['uid']])->update($account_list);
            /**
             * 修改订单状态
             */
            $ali_type['ali_type'] = '1';

            $merge_list = db('merge_order')->where(['merge_number'=>$merge_order_list['merge_number']])->find();
            $goods_type['type'] = '2';
            $goods_type['ali_type'] = '1';
            if ($merge_order_list['balance'] == '0.00') {
                $goods_type['pay_type'] = '1';
            }else{
                $goods_type['pay_type'] = '4';
                
            }
            $goods_type['end_total'] = $merge_list['money'];
            $goods['type'] = '2';
            $recordList['type'] = $goods_type['pay_type'];
            $recordList['uid'] = $merge_order_list['uid'];
            $recordList['merge_number'] = $merge_order_list['merge_number'];
            $recordList['ali_unit'] = $end_total;
            $recordList['balance_unit'] = $reduce_balance;
            // $recordList['balance_unit'] = $list['trade_no'];
            $recordList['time'] = date('Y-m-d H:i');

            db('record')->insert($recordList);
            // dump($recordList);
            // exit;
            if (!empty($merge_list)) {
                db('merge_order')->where(['merge_id'=>$merge_list['merge_id']])->update($ali_type);
                $merge_number = explode(",",$merge_list['number']);
                $number = '';
                foreach ($merge_number as $key => $value) {
                     $number .= "`number`="."'".$value."'"." or ";
                     // dump($value);
                     db('goods')->where(['number'=>$value])->update($goods);
                }
                $number = rtrim($number,'or ');

                // $interest['merge_number'] = $list['merge_number'];                             
                // $interest['uname'] = $list['uname'];                             
                // $interest['bank'] = $list['bank'];                             
                // $interest['bank_name'] = $list['bank_name'];                             
                // $interest['uid'] = $list['uid'];    
                if (db('goods_order')->where($number)->update($goods_type) > 0) {
                    
                    echo 'success';
                    exit;
                }  else{
                    echo 'fail';
                    exit;
                }                       

            }        
        }else{
            echo 'fail';
            exit;
        }

        
    }



    

    /**
     * 余额支付
     * @return [type] [description]
     */
    public function balance_pay()
    { 
    	$list = input('param.');
        $merge_number = input('param.merge_number');
        $uid = input('param.uid');
        // $reward_type = input('param.reward_type');
        // echo $reward_type;
        // exit;
        $merge_order_list = db('merge_order')->where(['merge_number'=>$merge_number])->find();
        $number_list = explode(",",$merge_order_list['number']);
        // dump($number_list);
        // exit;
        $number = null;
        foreach ($number_list as $key => $value) {
             $number .= "`number`="."'".$value."'"." or ";
 
        }
        $number = rtrim($number,'or ');
        // echo $number;
        $order_list = db('goods_order')->where($number)->select();
        $account = db('account')->where(['uid'=>$uid])->find();
        $count = null;
        foreach ($order_list as $key => $value) {
            // dump($value['total']);
            $count += $value['total'] + $value['freight'];
        }
        // echo $count - $account['integral'];
        // exit;
        

        // if ($account['integral'] > $count) {
        //     $account_list['integral'] = $account['integral'] - $count; //剩余积分
        //     $account_list['balance'] = $account['balance']; //剩余余额
        //     $reduce_integral = $account['integral'] - $account_list['integral'];   //扣除的积分
        //     $reduce_balance = '0';
        //     $end_total = '0'; //交易金额
        // }else if($account['balance'] > $count){
        //     $integral = $count - $account['integral']; 
        //     $account_list['balance'] = $account['balance'] - $integral; //剩余余额
        //     $reduce_balance = $account['balance'] - $account_list['balance']; //扣除余额
        //     $reduce_integral =$count - $integral; //扣除的积分
        //     $account_list['integral'] = $account['integral'] - $reduce_integral; //剩余的积分;
            
        //     $end_total = '0';
        // }else{
        //     $integral = $count - $account['integral']; 
        //     $reduce_integral =$count - $integral; //扣除的积分
        //     if ($integral > $account['balance']) {
        //         $balance = $integral - $account['balance'];
        //         $reduce_balance = $integral - $balance; //扣除余额
        //     }else{
        //         $balance =  $account['balance'] - $integral;
        //         $reduce_balance = $account['balance'] - $balance; //扣除余额
        //     }
            
        //     $account_list['integral'] = $account['integral'] - $reduce_integral; //剩余的积分;
        //     $account_list['balance']  = $account['balance'] - $reduce_balance; //剩余的余额
        //     $end_total = $count - $account['integral'] - $account['balance']; //交易金额
        // }
        if($account['balance'] > $count){
           
            $account_list['balance'] = $account['balance'] - $count; //剩余余额
            // $account_list['balance'] = $account['balance'] - $integral; 
            $reduce_balance = $account['balance'] - $account_list['balance']; //扣除余额
            // $reduce_integral =$count - $integral; //扣除的积分
            // $account_list['integral'] = $account['integral'] - $reduce_integral; //剩余的积分;
            $end_total = '0';
        }else{
            $end_total = $count - $account['balance']; //支付金额
            // $account_list['balance'] = $account['balance'] - $integral; 
            $reduce_balance = $count - $end_total; //扣除余额
            $account_list['balance'] = '0'; //剩余余额
        }
        $merge_list = db('merge_order')->where(['merge_number'=>$merge_number])->find();
       // dump($merge_list);
       // exit;
        if (!empty($merge_list)) {
          
          /**
           * 将扣除的余额存入记录
           */
          // dump($reduce_balance);
          if ($reduce_balance != '0') {
              $add_balance['reduce'] = $reduce_balance;
              $add_balance['uid'] = $uid;
              $add_balance['explain'] = '订单号 :'.$merge_list['merge_number'];
              $add_balance['notes'] = '购物抵扣';
              $add_balance['time'] = date('Y-m-d');
              $add_balance['number'] = $merge_list['merge_number'];
              // dump($add_balance);
              // exit;
              db('balance')->insert($add_balance);
          }

           /**
           * 将剩下的余额存入数据库
           */
          db('account')->where(['uid'=>$uid])->update($account_list);
          // echo '222';
          // exit;
          $ali_type['ali_type'] = '1';
          $goods_type['type'] = '2';
          $goods_type['ali_type'] = '1';
          $goods_type['pay_type'] = '3';
          $goods_type['end_total'] = $end_total;
          $goods['type'] = '2';
          /**
           * 对支付进行记录
           */
          $recordList['type'] = $goods_type['pay_type'];
          $recordList['uid'] = $uid;
          $recordList['merge_number'] = $merge_number;
          $recordList['ali_unit'] = '0';
          $recordList['wx_unit'] = '0';
          $recordList['balance_unit'] = $reduce_balance;
          $recordList['time'] = date('Y-m-d H:i');
          db('record')->insert($recordList);
          // dump($goods_type);
          // exit;
          db('merge_order')->where(['merge_id'=>$merge_list['merge_id']])->update($ali_type);
          $merge_number = explode(",",$merge_list['number']);
          $number = '';
          foreach ($merge_number as $key => $value) {
               $number .= "`number`="."'".$value."'"." or ";
               // dump($value);
               db('goods')->where(['number'=>$value])->update($goods);
          }
          $number = rtrim($number,'or ');
          db('goods_order')->where($number)->update($goods_type);
              

            /**
             * 处理积分/贴息操作
             */
            
        		$interest['merge_number'] = $list['merge_number'];                             
            $interest['uname'] = $list['uname'];                             
            $interest['bank'] = $list['bank'];                             
            $interest['bank_name'] = $list['bank_name'];                             
            $interest['uid'] = $list['uid'];    
            if (db('interest')->insert($interest) > 0) {
               
                echo json_encode(array("status"=>1,'message'=>'贴息成功!',"data"=>[]));
                exit;
            }  else{
                echo json_encode(array("status"=>2,'message'=>'选择贴息失败!',"data"=>[]));
                exit;
            }                                              
	                 
	   

            echo json_encode(array("status"=>1,'message'=>'支付成功!',"data"=>[]));
            exit;
        }else{
            echo json_encode(array("status"=>2,'message'=>'支付失败!',"data"=>[]));
            exit;
        }



    }

   // /**
   //  * 支付宝支付申请调用接口返回
   //  * @return [type] [description]
   //  */
   // public function pay()
   // {
   //      include_once ROOT_PATH.'extend/payment/autoload.php';
   //      include_once ROOT_PATH.'extend/payment/src/Common/PayException.php';
   //      include_once ROOT_PATH.'extend/payment/src/Client/Charge.php';
   //      // var_dump(date('Y-m-d H:i:s', 1502204401));
   //      // exit;
   //      // Charge::run();
   //      $config = require_once(ROOT_PATH.'extend/payment/examples/aliconfig.php');// 支付宝的配置信息
   //      $number = input('param.number');
   //      $order_list = db('goods_order')->where(['number'=>$number])->select();
   //      // dump($order_list);
   //      // exit;
   //      $goods_name = '';
   //      foreach ($order_list as $key => $value) {
   //          $goods_name .= $value['goods_name'].',';
   //      }
   //      $goods_name = rtrim($goods_name,', ');
   //      // dump($order_list[0]['total']);
   //      // exit;

   //      $channel = 'ali_web';
   //      $payData = [
   //          'body' => '',
   //          'subject' => $goods_name,
   //          'order_no' => $order_list[0]['number'],
   //          'timeout_express' => strtotime(date('Y-m-d H:i:s', strtotime("+10 minute"))),
   //          'amount' => '0.01',
   //          'return_param' => 'buy some',
   //          'goods_type' => 1,// 默认值为1，因此也可以省略
   //          'store_id' => '',// 没有就不设置
   //      ];

   //      try {
   //          $str = Charge::run($channel, $config, $payData);
   //      } catch (PayException $e) {
   //          // 异常处理
   //          exit;
   //      }

   //      echo htmlspecialchars($str);
   // }






    
}
